package com.inspur.jxpcxt.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.HttpConnectionParams;

import com.inspur.jxpcxt.constants.Constants;
import com.inspur.jxpcxt.service.StreamTools;

public class CommonService {
	/**
	 * 公共请求部分，只是返回的结果不同抽出为一个方法
	 * 
	 * @param path
	 * @param client
	 * @return
	 */
	public static String serviceRequest(String path, HttpClient client)
		{
			// GET方式请求
			HttpGet httpGet = new HttpGet(path);
			// 获取服务器返回的HttpResponse
			HttpResponse response = null;
			try {
				response = client.execute(httpGet);
			} catch (ClientProtocolException e1) {
				JXPCLog.e("ClientProtocolException e1");
				e1.printStackTrace();
				
				return "网络服务器未开启";
			} catch (IOException e1) {
				JXPCLog.e("IOException e1");
				e1.printStackTrace();
				return ""; 
			}

			// 设置连接时间超时
			HttpConnectionParams.setConnectionTimeout(client.getParams(),
					Constants.CONNECTIONTIMEOUT);
			// 读取超时
			HttpConnectionParams.setSoTimeout(client.getParams(),
					Constants.SOTIMEOUT);
			// 获取状态码
			int code = response.getStatusLine().getStatusCode();
			if (code == Constants.STATUSCODE) {
				// 获取返回的内容
				// 获取输入流
				InputStream is = null;
				try {
					is = response.getEntity().getContent();
				} catch (IllegalStateException e) {
					JXPCLog.e("IllegalStateException");
					e.printStackTrace();
					return "";
				} catch (IOException e) {
					JXPCLog.e("IOException e");
					e.printStackTrace();
					return "";
				}
				// 将输入流转化成字符串
				String text = StreamTools.readInputStream(is);
				return text;
			} else {
				return "服务器异常";
			}
		}
}
